package com.example.drainage.ui.certupload

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.sql.Timestamp
import java.text.SimpleDateFormat

class SurfaceViewDrawSign @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback, Runnable {

    private lateinit var mSurfaceHolder: SurfaceHolder

    //绘图的Canvas
    private var mCanvas: Canvas? = null

    //画笔
    private val mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

    //子线程标志位
    private var mIsThreadRunning = false

    // 轮训线程
    private var mThread: Thread? = null

    // 是否正在绘制
    private var isDrawing = false

    // View高度
    private var screenHeight = 0

    // View宽度
    private var screenWidth = 0

    private val pathList = mutableListOf<Path>()

    private var tempPath: Path? = null

    init {
        initView()
    }

    companion object {
        private const val TAG = "SurfaceViewDrawSign"

        private const val TIME_GIF = 50
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        // 频繁调用,使用线程池或Rxjava
        Log.d(TAG, "surfaceCreated() called with: holder = $holder")
        if (mThread != null && mThread!!.isAlive) {
            mThread!!.interrupt()
        }
        mIsThreadRunning = true
        mThread = Thread(this)
        mThread?.start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        mIsThreadRunning = false
        if (mThread != null && mThread!!.isAlive) {
            mThread!!.interrupt()
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        screenHeight = height
        screenWidth = width
    }

    override fun run() {
        while (mIsThreadRunning) {
            if (pathList.isEmpty()) {
                try {
                    drawSomething()
                    Thread.sleep(200)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            } else {
                val start = System.currentTimeMillis()
                drawSomething()
                val end = System.currentTimeMillis()
                if (end - start < TIME_GIF) {
                    try {
                        Thread.sleep(TIME_GIF - (end - start))
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        super.onTouchEvent(event)
        onTouchEventCall(event)
        return true
    }

    fun onTouchEventCall(event: MotionEvent): Boolean {
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                val path = Path()
                tempPath = path
                pathList.add(path)
                path.moveTo(event.x, event.y)
            }
            MotionEvent.ACTION_MOVE -> {
                tempPath?.lineTo(event.x, event.y)
            }
            /*MotionEvent.ACTION_UP,*/
            else -> {
                tempPath?.lineTo(event.x, event.y)
            }
        }
        return true
    }

    /**
     * 初始化View
     */
    private fun initView() {
        mSurfaceHolder = holder
        mSurfaceHolder.addCallback(this)
        isFocusable = true
        keepScreenOn = true
        isFocusableInTouchMode = true
        // 会覆盖到顶部标题/FallView上
//        setZOrderOnTop(true)
//        holder.setFormat(PixelFormat.TRANSLUCENT)
        mPaint.color = Color.BLACK
        mPaint.strokeWidth = 16f
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeJoin = Paint.Join.ROUND
        mPaint.strokeCap = Paint.Cap.ROUND;
    }

    private fun drawSomething() {
        if (isDrawing) {
            return
        }
        isDrawing = true
        try {
            //获得canvas对象
            mCanvas = mSurfaceHolder.lockCanvas()
            mCanvas?.apply {
                //绘制背景
//                drawColor(Color.TRANSPARENT)
                drawColor(Color.WHITE)
                pathList.forEach { path ->
                    drawPath(path, mPaint)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            isDrawing = false
            //释放canvas对象并提交画布
            if (mCanvas != null) {
                try {
                    mSurfaceHolder.unlockCanvasAndPost(mCanvas)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun reset() {
        pathList.clear()
    }

    fun checkLineCount(count: Int): Boolean {
        return pathList.size >= count
    }

    fun saveImgToLocal(key: String?, callBack: (Boolean, String?) -> Unit) {
        val tailStr = if (key == null) "_sign" else "_sign_$key"
        val file = File(context.externalCacheDir, "${getTempFileName()}$tailStr.jpg")
        val out = FileOutputStream(file)
        var loadSuccess = false
        try {
            var bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            canvas.apply {
                drawColor(Color.WHITE)
                pathList.forEach { path ->
                    drawPath(path, mPaint)
                }
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
            loadSuccess = true
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                out.flush()
                out.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            callBack(loadSuccess, file.absolutePath)
        }
    }

    private fun getTempFileName(): String {
        val format = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
        return format.format(Timestamp(System.currentTimeMillis()))
    }
}